package com.cavedroid;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;

public class CaveRenderer implements GLSurfaceView.Renderer {
	
	Cave cave;
	
	public boolean fog;
	
	public boolean shortCutoff;
	
	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		gl.glMatrixMode(GL10.GL_PROJECTION);
	    gl.glLoadIdentity();
		gl.glViewport(0, 0, width, height);
		
		float cutoff;
		if (shortCutoff) {
			cutoff = 10;
		} else {
			cutoff = 20;
		}
		float fogColour[] = {0.0f, 0.0f, 0.0f, 1.0f};
		gl.glClearColor(0, 0, 0, 1);
		
		gl.glEnable(GL10.GL_DEPTH_TEST);
		gl.glDepthFunc(GL10.GL_LEQUAL);

		if (fog) {
	    	gl.glEnable(GL10.GL_FOG);
	    	gl.glFogx(GL10.GL_FOG_MODE, GL10.GL_LINEAR);
	    	gl.glFogfv(GL10.GL_FOG_COLOR, fogColour, 0);
	    	gl.glFogf(GL10.GL_FOG_DENSITY, 0.35f);
	    	gl.glFogf(GL10.GL_FOG_START, 17.5f);
	    	gl.glFogf(GL10.GL_FOG_END, 19.5f);
	    	gl.glHint(GL10.GL_FOG_HINT, GL10.GL_NICEST);
	    	cutoff += 3; //Weird opengl bug
	    } else {
	    	gl.glDisable(GL10.GL_FOG);
	    }
		
		gl.glEnable(GL10.GL_POLYGON_OFFSET_FILL);
		gl.glPolygonOffset(1.5f, 1);
		
		gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); 

	    float ratio = (float) width / height;
	    gl.glFrustumf(-ratio, ratio, -1, 1, 1, cutoff);
	    
	    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		
	}

	@Override
	public void onDrawFrame(GL10 gl) {
		cave.draw(gl);
	}

}
